/*******************************************************************************************
*
*   Artillery Simulator using raylib
*   一个使用 raylib 模拟防空炮的游戏
*
*   Features:
*   - Fixed camera view.
*   - Launch shells with spacebar.
*   - Aim using mouse click/drag to define initial velocity vector.
*   - Shells follow parabolic trajectory under gravity.
*   - Trajectory is visualized with random semi-transparent colored trails.
*   - Visualized initial velocity vector with angle and magnitude display.
*   - Targets (airplanes) spawn periodically and can be shot down.
*   - Hit targets blink before disappearing.
*   - Pause and velocity vector display modes.
*
********************************************************************************************/

#include "raylib.h"
#include "raymath.h"
#include <vector>   // 用于 std::vector 容器
#include <cstdlib>  // 用于 rand() 和 srand() 函数 (随机数)
#include <ctime>    // 用于 time() 函数 (获取时间，用作随机数种子)
#include <cmath>    // 用于 atan2f, sqrtf (虽然 Vector2Length 内部会用)
#include <algorithm> // 新增：用于 std::remove_if

//----------------------------------------------------------------------------------
// 常量定义 (Defines)
//----------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 600;
const float GRAVITY = 98.0f;          // 重力加速度 (像素/秒^2), 正值向下
const Vector2 launchPosition = { screenWidth / 2.0f, screenHeight - 50.0f }; // 发射点 (屏幕底部中央)
const float SHELL_RADIUS = 8.0f;      // 炮弹半径 (原 BALL_RADIUS)
const float VELOCITY_SCALE_FACTOR = 1.0f; // 速度缩放因子
const int MAX_TRAIL_POINTS = 300;     // 每个炮弹/炸弹轨迹点的最大数量
const float VELOCITY_ARROW_SCALE_FACTOR = 0.5f; // 用于绘制炮弹/目标/炸弹瞬时速度箭头的缩放因子

// 新增：目标相关常量
const float TARGET_WIDTH = 60.0f;
const float TARGET_HEIGHT = 20.0f;
const float TARGET_SPAWN_Y = 200.0f;    // 飞机生成的高度
const float TARGET_SPEED = 100.0f;   // 飞机水平速度 (像素/秒)
const float TARGET_SPAWN_INTERVAL = 10.0f; // 飞机生成间隔 (秒)
const int TARGET_MAX_BLINKS = 3;         // 飞机被击中后闪烁次数
const float TARGET_BLINK_DURATION = 0.15f; // 每次闪烁（亮或暗）的持续时间

// 新增：炸弹相关常量
const float BOMB_RADIUS = 5.0f;       // 炸弹半径
const Color BOMB_COLOR = BLACK;       // 炸弹颜色
const Color BOMB_TRAIL_COLOR = DARKGRAY; // 炸弹轨迹颜色

//----------------------------------------------------------------------------------
// 结构体定义 (Structures)
//----------------------------------------------------------------------------------
// 炮弹结构体 (原 Ball)
typedef struct Shell {
    Vector2 position;                   // 当前位置
    Vector2 velocity;                   // 当前速度 (x分量, y分量)
    Color trailColor;                   // 轨迹颜色
    std::vector<Vector2> trailPoints;   // 存储轨迹点的向量
    bool active;                        // 炮弹是否活动
} Shell;

// 新增：目标 (飞机) 结构体
typedef struct Target {
    Rectangle rect;                     // 飞机的位置和大小
    Vector2 velocity;                   // 飞机的速度
    Color color;                        // 飞机颜色
    bool active;                        // 飞机是否活动
    bool isHit;                         // 是否被击中，正在播放闪烁动画
    int blinksRemaining;                // 剩余闪烁次数
    float blinkTimer;                   // 当前闪烁状态的计时器
    bool isVisibleDuringBlink;          // 闪烁时是否可见
    // bool bombDropped;                // 新增：此飞机是否已投弹  <- 这行可以移除或注释掉
    int bombsAvailable;                 // 新增：此飞机可用的炸弹数量
} Target;

// 新增：炸弹结构体
typedef struct Bomb {
    Vector2 position;
    Vector2 velocity;
    std::vector<Vector2> trailPoints;
    bool active;
} Bomb;

//----------------------------------------------------------------------------------
// 全局变量 (Global Variables)
//----------------------------------------------------------------------------------
std::vector<Shell> shells; // 存储所有炮弹 (原 balls)
std::vector<Target> targets; // 新增：存储所有目标
std::vector<Bomb> bombs;     // 新增：存储所有炸弹
Vector2 aimPoint;        // 鼠标点击设置的瞄准点
bool aimPointSet = false; // 标记瞄准点是否已设置
bool showVelocityVectors = false; // 标记是否显示速度矢量
bool isPaused = false; // 标记游戏是否暂停
float targetSpawnTimer = 0.0f; // 新增：飞机生成计时器
bool playerBombed = false; // 新增：标记玩家是否被炸

//----------------------------------------------------------------------------------
// 函数声明 (Function Declarations)
//----------------------------------------------------------------------------------
void LaunchNewShell(Vector2 initialVelocity); // (原 LaunchNewBall)
void UpdateActiveShells(float deltaTime);     // (原 UpdateActiveBalls)
void DrawSimulation();
void DrawAimingAssistance();
void DrawShellTrails();                       // (原 DrawBallTrails)
void DrawVectorArrow(Vector2 start, Vector2 end, float thickness, Color color);

// 新增：目标相关函数声明
void SpawnNewTarget();
void UpdateTargets(float deltaTime);
void DrawTargets();
void HandleCollisions(); // 将包含炮弹对飞机的碰撞

// 新增：炸弹相关函数声明
void DropBombFromTarget(Target& target);
void UpdateBombs(float deltaTime);
void DrawBombs();
void HandleBombCannonCollision(); // 处理炸弹与炮台的碰撞
void ResetGame();                 // 新增：重置游戏状态的函数声明
//------------------------------------------------------------------------------------
// 程序主入口点 (Program main entry point)
//------------------------------------------------------------------------------------
int main(void)
{
    // 初始化 (Initialization)
    //--------------------------------------------------------------------------------------
    InitWindow(screenWidth, screenHeight, "Artillery Simulator - raylib"); // 窗口标题更改
    SetTargetFPS(60);

    srand(time(NULL));

    aimPoint = launchPosition;
    targetSpawnTimer = TARGET_SPAWN_INTERVAL; // 立即准备生成第一个目标或等待第一个间隔
    //--------------------------------------------------------------------------------------

    // 主游戏循环 (Main game loop)
    while (!WindowShouldClose())
    {
        // 更新逻辑 (Update)
        //----------------------------------------------------------------------------------
        float deltaTime = GetFrameTime();

        // 处理用户输入 (Handle Input)
        if (playerBombed) // 如果玩家已被炸
        {
            if (IsKeyPressed(KEY_SPACE)) // 按空格重新开始
            {
                ResetGame();
            }
        }
        else // 玩家未被炸，正常游戏输入
        {
            if (IsMouseButtonDown(MOUSE_BUTTON_LEFT))
            {
                aimPoint = GetMousePosition();
                aimPointSet = true;
            }

            if (IsKeyPressed(KEY_SPACE) && aimPointSet && !isPaused)
            {
                Vector2 initialVelocityDirection = Vector2Subtract(aimPoint, launchPosition);
                Vector2 initialVelocity = Vector2Scale(initialVelocityDirection, VELOCITY_SCALE_FACTOR);
                LaunchNewShell(initialVelocity);
            }

            if (IsKeyPressed(KEY_D)) showVelocityVectors = !showVelocityVectors;
            if (IsKeyPressed(KEY_P)) isPaused = !isPaused;

            if (IsKeyPressed(KEY_B) && !isPaused) // 新增：飞机投弹
            {
                for (int i = targets.size() - 1; i >= 0; --i) // 从最新的飞机开始检查
                {
                    // 修改下面这行条件判断
                    if (targets[i].active && targets[i].bombsAvailable > 0 && !targets[i].isHit)
                    {
                        DropBombFromTarget(targets[i]);
                        break; // 一次只投一个
                    }
                }
            }
        }


        if (!isPaused && !playerBombed) // 仅在未暂停且玩家未被炸时更新游戏逻辑
        {
            // 目标生成逻辑
            targetSpawnTimer -= deltaTime;
            if (targetSpawnTimer <= 0)
            {
                SpawnNewTarget();
                targetSpawnTimer = TARGET_SPAWN_INTERVAL;
            }

            UpdateActiveShells(deltaTime);
            UpdateTargets(deltaTime); 
            UpdateBombs(deltaTime);       // 新增：更新炸弹
            HandleCollisions();       
            HandleBombCannonCollision();  // 新增：处理炸弹与炮台碰撞
        }
        //----------------------------------------------------------------------------------

        // 绘制阶段 (Draw)
        //----------------------------------------------------------------------------------
        BeginDrawing();
            ClearBackground(RAYWHITE);
            DrawSimulation();

            // UI提示文字
            DrawText("Left-click and drag to set aim point", 10, 10, 20, DARKGRAY);
            DrawText("Press SPACE to launch shell", 10, 40, 20, DARKGRAY);
            if (aimPointSet)
            {
                DrawText(TextFormat("Aim Point: (%.0f, %.0f)", aimPoint.x, aimPoint.y), 10, 70, 15, GRAY);
                Vector2 velDirUnscaled = Vector2Subtract(aimPoint, launchPosition);
                Vector2 actualInitialVelocity = Vector2Scale(velDirUnscaled, VELOCITY_SCALE_FACTOR);
                float magnitude = Vector2Length(actualInitialVelocity);
                float angleRadians = atan2f(launchPosition.y - aimPoint.y, aimPoint.x - launchPosition.x); // Y轴反向
                float angleDegrees = angleRadians * RAD2DEG;

                DrawText(TextFormat("Est. Initial Velocity: <%.1f, %.1f>", actualInitialVelocity.x, actualInitialVelocity.y), 10, 95, 15, GRAY);
                DrawText(TextFormat("Angle: %.1f degrees", angleDegrees), 10, 120, 15, DARKGREEN);
                DrawText(TextFormat("Magnitude (Speed): %.1f pixels/sec", magnitude), 10, 145, 15, DARKGREEN);
            }
            DrawText(TextFormat("Show Velocity Vectors (D): %s", showVelocityVectors ? "ON" : "OFF"), 10, 170, 15, DARKBLUE);
            DrawText(TextFormat("Pause (P): %s", isPaused ? "ON" : "OFF"), 10, 195, 15, DARKBLUE);
            DrawText(TextFormat("Drop Bomb (B)"), 10, 220, 15, DARKBLUE); // 新增提示
            DrawText(TextFormat("Targets: %zu Shells: %zu Bombs: %zu", targets.size(), shells.size(), bombs.size()), screenWidth - 250, 10, 15, DARKGRAY);


            if (playerBombed) // 新增：如果玩家被炸，显示提示信息
            {
                const char* gameOverText = "YOU HAVE BEEN BOMBED!";
                int textWidth = MeasureText(gameOverText, 40);
                DrawText(gameOverText, screenWidth/2 - textWidth/2, screenHeight/2 - 40, 40, RED); // 向上调整Y坐标

                const char* restartText = "Press SPACE to Restart";
                int restartTextWidth = MeasureText(restartText, 20);
                DrawText(restartText, screenWidth/2 - restartTextWidth/2, screenHeight/2 + 10, 20, DARKGRAY); // 新增重启提示
            }

        EndDrawing();
        //----------------------------------------------------------------------------------
    }

    // 反初始化/清理 (De-Initialization)
    //--------------------------------------------------------------------------------------
    CloseWindow();
    //--------------------------------------------------------------------------------------

    return 0;
}

//----------------------------------------------------------------------------------
// 函数定义 (Function Definitions)
//----------------------------------------------------------------------------------

// 新增：重置游戏状态的函数
void ResetGame()
{
    // 清空所有动态对象
    shells.clear();
    targets.clear();
    bombs.clear();

    // 重置游戏状态变量
    playerBombed = false;
    isPaused = false;       // 如果希望游戏结束时暂停，这里可以保持 isPaused = true，并在重启时设为 false
    aimPointSet = false;
    aimPoint = launchPosition; // 重置瞄准点
    targetSpawnTimer = TARGET_SPAWN_INTERVAL; // 重置目标生成计时器

    // 如果有分数等其他需要重置的变量，也在这里添加
}

// (原 DrawVectorArrow) - 无变化，保持原样
void DrawVectorArrow(Vector2 start, Vector2 end, float thickness, Color color)
{
    // 如果起点和终点太近，则不绘制箭头，避免视觉混乱
    if (Vector2Distance(start, end) < 1.0f) return;

    DrawLineEx(start, end, thickness, color);

    // 箭头头部参数
    float arrowHeadLength = 12.0f;
    float arrowHeadAngle = 25.0f; // 箭头翼与主线的夹角 (度)

    Vector2 direction = Vector2Normalize(Vector2Subtract(end, start));

    // 计算箭头翼的两个点
    Vector2 wing1End = Vector2Add(end, Vector2Rotate(Vector2Scale(direction, -arrowHeadLength), -arrowHeadAngle * DEG2RAD));
    Vector2 wing2End = Vector2Add(end, Vector2Rotate(Vector2Scale(direction, -arrowHeadLength), arrowHeadAngle * DEG2RAD));
    
    DrawLineEx(end, wing1End, thickness, color);
    DrawLineEx(end, wing2End, thickness, color);
}


// 发射新炮弹的函数 (原 LaunchNewBall)
void LaunchNewShell(Vector2 initialVelocity)
{
    Shell newShell;
    newShell.position = launchPosition;
    newShell.velocity = initialVelocity;
    newShell.trailColor = (Color){
        (unsigned char)GetRandomValue(50, 200),
        (unsigned char)GetRandomValue(50, 200),
        (unsigned char)GetRandomValue(50, 200),
        150
    };
    newShell.active = true;
    newShell.trailPoints.clear();
    newShell.trailPoints.push_back(newShell.position);
    shells.push_back(newShell);
}

// 更新所有活动炮弹状态的函数 (原 UpdateActiveBalls)
void UpdateActiveShells(float deltaTime)
{
    for (size_t i = 0; i < shells.size(); ++i)
    {
        if (shells[i].active)
        {
            shells[i].velocity.y += GRAVITY * deltaTime;
            shells[i].position = Vector2Add(shells[i].position, Vector2Scale(shells[i].velocity, deltaTime));

            if (shells[i].trailPoints.size() < MAX_TRAIL_POINTS)
            {
                shells[i].trailPoints.push_back(shells[i].position);
            }

            // 炮弹飞出屏幕或落地后失效
            if (shells[i].position.y > screenHeight + SHELL_RADIUS * 2 || // 飞出底部
                shells[i].position.y < -SHELL_RADIUS * 10 || // 飞出顶部过远
                shells[i].position.x < -SHELL_RADIUS * 10 || // 飞出左侧过远
                shells[i].position.x > screenWidth + SHELL_RADIUS * 10) // 飞出右侧过远
            {
                shells[i].active = false;
            }
        }
    }
    // 移除不活动的炮弹b
    shells.erase(std::remove_if(shells.begin(), shells.end(), [](const Shell& s){ return !s.active; }), shells.end());
}

// 新增：生成新目标 (飞机)
void SpawnNewTarget()
{
    Target newTarget;
    newTarget.rect.width = TARGET_WIDTH;
    newTarget.rect.height = TARGET_HEIGHT;
    newTarget.rect.y = TARGET_SPAWN_Y;

    bool spawnFromLeft = (GetRandomValue(0, 1) == 0); // 随机决定从左边还是右边生成
    if (spawnFromLeft)
    {
        newTarget.rect.x = -TARGET_WIDTH; // 从屏幕左外侧开始
        newTarget.velocity = (Vector2){ TARGET_SPEED, 0 };
    }
    else
    {
        newTarget.rect.x = screenWidth; // 从屏幕右外侧开始
        newTarget.velocity = (Vector2){ -TARGET_SPEED, 0 };
    }

    newTarget.color = DARKGRAY; // 飞机颜色
    newTarget.active = true;
    newTarget.isHit = false;
    newTarget.blinksRemaining = 0;
    newTarget.blinkTimer = 0.0f;
    newTarget.isVisibleDuringBlink = true;
    // newTarget.bombDropped = false; // 新增：初始化未投弹 <- 删除或注释掉此行
    newTarget.bombsAvailable = 2;   // 确保此行存在并设置飞机初始炸弹数量
    targets.push_back(newTarget);
}

// 新增：更新目标状态
void UpdateTargets(float deltaTime)
{
    for (size_t i = 0; i < targets.size(); ++i)
    {
        if (targets[i].active)
        {
            if (targets[i].isHit) // 如果被击中，处理闪烁动画
            {
                targets[i].blinkTimer -= deltaTime;
                if (targets[i].blinkTimer <= 0)
                {
                    targets[i].isVisibleDuringBlink = !targets[i].isVisibleDuringBlink; // 切换可见性
                    targets[i].blinkTimer = TARGET_BLINK_DURATION;
                    targets[i].blinksRemaining--;

                    if (targets[i].blinksRemaining < 0) // 闪烁完成
                    {
                        targets[i].active = false; // 销毁飞机
                    }
                }
            }
            else // 正常移动
            {
                targets[i].rect.x += targets[i].velocity.x * deltaTime;
                targets[i].rect.y += targets[i].velocity.y * deltaTime; // 如果有垂直移动

                // 目标飞出屏幕后失效
                if (targets[i].velocity.x > 0 && targets[i].rect.x > screenWidth) targets[i].active = false;
                if (targets[i].velocity.x < 0 && targets[i].rect.x < -targets[i].rect.width) targets[i].active = false;
            }
        }
    }
    // 移除不活动的目标
    targets.erase(std::remove_if(targets.begin(), targets.end(), [](const Target& t){ return !t.active; }), targets.end());
}

// 新增：处理碰撞
void HandleCollisions()
{
    for (size_t i = 0; i < shells.size(); ++i)
    {
        if (!shells[i].active) continue;

        for (size_t j = 0; j < targets.size(); ++j)
        {
            if (!targets[j].active || targets[j].isHit) continue; // 如果目标不活动或已在播放击中动画，则跳过

            // 碰撞检测：炮弹(圆) vs 目标(矩形)
            if (CheckCollisionCircleRec(shells[i].position, SHELL_RADIUS, targets[j].rect))
            {
                shells[i].active = false; // 炮弹失效

                targets[j].isHit = true; // 标记目标被击中
                targets[j].blinksRemaining = TARGET_MAX_BLINKS * 2 -1; // 总共状态改变次数 (亮->暗->亮->暗->亮->暗)
                targets[j].blinkTimer = TARGET_BLINK_DURATION;
                targets[j].isVisibleDuringBlink = false; // 初始为不可见（第一次闪烁）
                targets[j].color = RED; // 可以改变颜色表示被击中
                
                // 不需要立即移除目标，UpdateTargets会处理闪烁和最终移除
                break; // 一个炮弹只击中一个目标
            }
        }
    }
}


// 绘制整个模拟场景的函数
void DrawSimulation()
{
    // 绘制地面线
    DrawLine(0, (int)launchPosition.y + (int)(SHELL_RADIUS/2), screenWidth, (int)launchPosition.y + (int)(SHELL_RADIUS/2), DARKGRAY);

    // 绘制发射点标记 (可以画一个简单的炮台)
    DrawRectangle((int)launchPosition.x -10, (int)launchPosition.y - 20, 20, 20, DARKBLUE);
    DrawCircleV(launchPosition, 5, BLUE);


    DrawAimingAssistance();
    DrawShellTrails(); // (原 DrawBallTrails)
    DrawTargets();     // 新增：绘制目标
    DrawBombs();       // 新增：绘制炸弹

    // 绘制所有活动的炮弹
    for (const auto& shell : shells) // (原 balls)
    {
        if (shell.active)
        {
            DrawCircleV(shell.position, SHELL_RADIUS, MAROON);

            if (showVelocityVectors)
            {
                Vector2 pos = shell.position;
                Vector2 vel = shell.velocity;
                Vector2 totalVelEnd = Vector2Add(pos, Vector2Scale(vel, VELOCITY_ARROW_SCALE_FACTOR));
                DrawVectorArrow(pos, totalVelEnd, 1.5f, BLUE);
                Vector2 horizontalVel = { vel.x, 0.0f };
                Vector2 horizontalVelEnd = Vector2Add(pos, Vector2Scale(horizontalVel, VELOCITY_ARROW_SCALE_FACTOR));
                DrawVectorArrow(pos, horizontalVelEnd, 1.5f, RED);
                Vector2 verticalVel = { 0.0f, vel.y };
                Vector2 verticalVelEnd = Vector2Add(pos, Vector2Scale(verticalVel, VELOCITY_ARROW_SCALE_FACTOR));
                DrawVectorArrow(pos, verticalVelEnd, 1.5f, GREEN);
            }
        }
    }
}

// 绘制瞄准辅助线的函数
void DrawAimingAssistance()
{
    if (aimPointSet)
    {
        // 从发射点到瞄准点绘制一条代表初速度方向的线 (不一定是实际速度矢量)
        // 实际发射的炮弹速度会根据 VELOCITY_SCALE_FACTOR 缩放
        DrawVectorArrow(launchPosition, aimPoint, 2.0f, SKYBLUE); // 瞄准线颜色调整
        DrawCircleV(aimPoint, 5, GRAY);
    }
}

// 绘制炮弹轨迹的函数 (原 DrawBallTrails)
void DrawShellTrails()
{
    for (const auto& shell : shells)
    {
        if (shell.active && shell.trailPoints.size() > 1)
        {
            for (size_t i = 0; i < shell.trailPoints.size(); ++i)
            {
                DrawCircleV(shell.trailPoints[i], 2.0f, shell.trailColor);
            }
        }
    }
}

// 新增：绘制目标 (飞机)
void DrawTargets()
{
    for (const auto& target : targets)
    {
        if (target.active)
        {
            if (target.isHit) // 如果被击中且在闪烁
            {
                if (target.isVisibleDuringBlink)
                {
                    DrawRectangleRec(target.rect, ORANGE); // 闪烁时用不同颜色
                }
                // else 不绘制，实现闪烁的“暗”状态
            }
            else // 正常状态
            {
                DrawRectangleRec(target.rect, target.color);
            }

            // 如果需要显示飞机的速度矢量
            if (showVelocityVectors && !target.isHit) // 不在被击中动画时显示
            {
                 Vector2 center = { target.rect.x + target.rect.width / 2, target.rect.y + target.rect.height / 2 };
                 Vector2 velEnd = Vector2Add(center, Vector2Scale(target.velocity, VELOCITY_ARROW_SCALE_FACTOR * 2)); // 飞机速度矢量可以更长一些
                 DrawVectorArrow(center, velEnd, 1.5f, PURPLE);
            }
        }
    }
}

// 新增：绘制炸弹
void DrawBombs()
{
    for (const auto& bomb : bombs)
    {
        if (bomb.active)
        {
            // 绘制炸弹轨迹
            if (bomb.trailPoints.size() > 1)
            {
                for (size_t i = 0; i < bomb.trailPoints.size(); ++i)
                {
                    DrawCircleV(bomb.trailPoints[i], 1.0f, BOMB_TRAIL_COLOR); // 轨迹点小一些
                }
            }
            // 绘制炸弹本身
            DrawCircleV(bomb.position, BOMB_RADIUS, BOMB_COLOR);

            // 绘制速度矢量 (如果开启)
            if (showVelocityVectors)
            {
                Vector2 pos = bomb.position;
                Vector2 vel = bomb.velocity;
                Vector2 totalVelEnd = Vector2Add(pos, Vector2Scale(vel, VELOCITY_ARROW_SCALE_FACTOR));
                DrawVectorArrow(pos, totalVelEnd, 1.0f, DARKBLUE); // 炸弹总速度矢量

                Vector2 horizontalVel = { vel.x, 0.0f };
                Vector2 horizontalVelEnd = Vector2Add(pos, Vector2Scale(horizontalVel, VELOCITY_ARROW_SCALE_FACTOR));
                DrawVectorArrow(pos, horizontalVelEnd, 1.0f, ORANGE); // 炸弹水平速度

                Vector2 verticalVel = { 0.0f, vel.y };
                Vector2 verticalVelEnd = Vector2Add(pos, Vector2Scale(verticalVel, VELOCITY_ARROW_SCALE_FACTOR));
                DrawVectorArrow(pos, verticalVelEnd, 1.0f, PURPLE); // 炸弹垂直速度
            }
        }
    }
}

// 新增：飞机投弹
void DropBombFromTarget(Target& target)
{
    TraceLog(LOG_INFO, "DropBombFromTarget called."); // 调试信息
    if (!target.active || target.bombsAvailable <= 0) { // 修改条件：检查 bombsAvailable
        TraceLog(LOG_INFO, "  DropBombFromTarget: Target not active or no bombs available. Returning."); // 调试信息
        return;
    }

    Bomb newBomb;
    newBomb.position = (Vector2){ target.rect.x + target.rect.width / 2, target.rect.y + target.rect.height };
    newBomb.velocity = (Vector2){ target.velocity.x, 0.0f }; // 平抛，初始垂直速度为0
    newBomb.active = true;
    newBomb.trailPoints.clear();
    newBomb.trailPoints.push_back(newBomb.position);
    bombs.push_back(newBomb);
    TraceLog(LOG_INFO, "  Bomb added. Total bombs: %zu", bombs.size()); // 调试信息

    target.bombsAvailable--; // 修改：减少可用炸弹数量
    // target.bombDropped = true; // 标记此飞机已投弹 <- 删除或注释掉此行
}

// 新增：更新炸弹状态
void UpdateBombs(float deltaTime)
{
    for (size_t i = 0; i < bombs.size(); ++i)
    {
        if (bombs[i].active)
        {
            bombs[i].velocity.y += GRAVITY * deltaTime; // 受重力影响
            bombs[i].position = Vector2Add(bombs[i].position, Vector2Scale(bombs[i].velocity, deltaTime));

            if (bombs[i].trailPoints.size() < MAX_TRAIL_POINTS)
            {
                bombs[i].trailPoints.push_back(bombs[i].position);
            }

            // 炸弹飞出屏幕或落地后失效
            if (bombs[i].position.y > screenHeight + BOMB_RADIUS * 2 || // 飞出底部 (或击中地面)
                bombs[i].position.y < -BOMB_RADIUS * 10 ||             // 飞出顶部过远
                bombs[i].position.x < -BOMB_RADIUS * 10 ||             // 飞出左侧过远
                bombs[i].position.x > screenWidth + BOMB_RADIUS * 10)  // 飞出右侧过远
            {
                bombs[i].active = false;
            }
        }
    }
    // 移除不活动的炸弹
    bombs.erase(std::remove_if(bombs.begin(), bombs.end(), [](const Bomb& b){ return !b.active; }), bombs.end());
}

// 新增：处理炸弹与炮台的碰撞
void HandleBombCannonCollision()
{
    if (playerBombed) return; // 如果已经被炸，不再检测

    Rectangle cannonRect = { launchPosition.x - 10, launchPosition.y - 20, 20, 20 }; // 炮台的碰撞区域

    for (size_t i = 0; i < bombs.size(); ++i)
    {
        if (bombs[i].active)
        {
            if (CheckCollisionCircleRec(bombs[i].position, BOMB_RADIUS, cannonRect))
            {
                bombs[i].active = false; // 炸弹失效
                playerBombed = true;     // 标记玩家被炸
                isPaused = true;         // 暂停游戏
                // 可以在这里播放爆炸声音或动画等
                break; // 一旦被炸，停止检测其他炸弹
            }
        }
    }
}